var canvas = $('#canvas')[0];
var canvasW = canvas.width,
    canvasH = canvas.height;
var stage = new createjs.Stage(canvas);
createjs.Touch.enable(stage);
var lefts, tops, scaleVal, rotates = 0,
    ctrEle = null;
createjs.Ticker.timingMode = createjs.Ticker.RAF;
createjs.Ticker.addEventListener("tick", tick);
createjs.Ticker.setFPS(60);
function tick(event) {
    stage.update(event);
}

// 添加场景背景
function AddShpFun(num) {
    remCtrEle="";
    stage.removeAllChildren();
    var TimgBg = new Image();
    TimgBg.src = _cdnUrl+"img/"+_sex+'/'+_chang+"/chang.jpg";
    TimgBg.onload = function () {
        var teaTable = new createjs.Bitmap(_cdnUrl+"img/"+_sex+'/'+_chang+"/chang.jpg");
        stage.addChild(teaTable);
        stage.setChildIndex(teaTable, 1);
        teaTable.x = 0;
        teaTable.y = 0;
    };
     
}




var offset, update = false, idx = 0;
var remCtrEle;//是否是人
var ChildIndex;//图层层级
var Firstadd = true;//是否是第一次添加
function Addicofun(idName,url, ren, IsSUcRen, Ispendant) {
    $(".game_menutip").remove();
    // url 图片地址
    // ren 是否是人物
    // 是否有人物在里面
    idx++;
    var imgBg = new Image();
    imgBg.src = url;
    imgBg.onload = function () {
        var cPhoto = new createjs.Bitmap(imgBg);
        rotates = cPhoto.rotation = 0;
        cPhoto.name = "bmp_" + idx;
        cPhoto.idName=idName;
        cPhoto.scaleX = cPhoto.scaleY = scaleVal = 1;
        cPhoto.regX = imgBg.width / 2;
        cPhoto.regY = imgBg.height / 2;
        cPhoto.x = lefts = canvasW / 2;
        cPhoto.y = tops = canvasH / 2.8;
        if (IsSUcRen) {
            cPhoto.rotation = remCtrEle.rotation;
            cPhoto.scaleX = cPhoto.scaleY = scaleVal = remCtrEle.scaleY;
            cPhoto.x = lefts = remCtrEle.x;
            cPhoto.y = tops = remCtrEle.y;
        }
        var oFrame = new createjs.Container();
        oFrame.addChild(cPhoto);
        if (Firstadd == true) {
            Firstadd = false;
            $(".gametip").show();
            setTimeout(function () {
                $(".gametip").hide();
            },2000)
        }
        stage.addChild(oFrame);
        // 判断为人物底图最底层
        ctrEle = cPhoto;
        if (ren == true) {
            $(".game_ok").show();
            remCtrEle = ctrEle;
            //stage.setChildIndex(oFrame, 1);
        } else { }
        if (Ispendant == true) {
            ChildIndex = stage.getNumChildren() - 1;
        } else {
            if (ChildIndex > 1) {
                stage.setChildIndex(oFrame, ChildIndex - 1);
            }
        }
        

        function ctrEleAM() {
            createjs.Tween.get(ctrEle, {loop: false})
                .to({scaleX: ctrEle.scaleX + 0.02, scaleY: ctrEle.scaleX + 0.02}, 100)
                .to({scaleX: ctrEle.scaleX, scaleY: ctrEle.scaleX}, 100, createjs.Ease.quadOut)
                .call(function () {
                    createjs.Tween.get(ctrEle, {loop: false})
                        .to({
                            scaleX: ctrEle.scaleX + 0.02,
                            scaleY: ctrEle.scaleX + 0.02
                        }, 100).to({scaleX: ctrEle.scaleX, scaleY: ctrEle.scaleX}, 100, createjs.Ease.quadOut)
                        .call(function () {
                            Isren = true;
                        });
                });
        }

        ctrEleAM();
        addCtr(ctrEle);
        update = true;
        cPhoto.on("mousedown", function (evt) {
            deleteCtr();
            update = true;
            lefts = evt.target.x;
            tops = evt.target.y;
            ctrEle = oFrame.getChildByName(cPhoto.name);
            ctrEleAM();
            addCtr(ctrEle);
            // 不是人物选中的在最上层
            if (ren == true) {
                remCtrEle = ctrEle;
                //stage.setChildIndex(oFrame, 1);
            } else {}
                if (Ispendant == true) {
                    stage.setChildIndex(oFrame, stage.getNumChildren() - 1);
                } else {
                    if (ChildIndex > 1) {
                        stage.setChildIndex(oFrame, stage.getNumChildren() - 2);
                    } else {
                        stage.removeChild(oFrame);
                        stage.addChild(oFrame)
                    }

                }

            
            stage.update(this);

        });
        cPhoto.on("pressup", function (evt) {
            // update = false;
            // console.log(evt)
        });
    };
}









//合并人物
var PerArr = [1,1,1,1,1,1];//姿势，服装,宠物，道具, 文字
var DressCanvas = $('#DressCanvas')[0];
var DressStage = new createjs.Stage(DressCanvas);
var Isren = true;//是否有添加成功

function AddRenTemp(_url) {
	Isren = false;
    DressStage.removeAllChildren();
    // 姿势
    var ren = new Image();
    ren.src = _url;
    ren.onload = function () {
        DressCanvas.width = ren.width/2;
        DressCanvas.height = ren.height/2;
        var Tren = new createjs.Bitmap(ren);
        Tren.scaleX=0.5;
        Tren.scaleY=0.5;
        DressStage.addChild(Tren);
        DressStage.update();
        var photos = DressStage.toDataURL();//生成图片地址，1为质量
        if (photos) {
            if (remCtrEle) {
                stage.removeChild(remCtrEle.parent);
                Addicofun('ren',photos, true, true);
                return;
            }
            Addicofun('ren',photos, true);
        }
    }
}


function AddOther(idName,_url, scale) {
    DressStage.removeAllChildren();
    var other = new Image();
    other.src = _url;
    other.onload = function () {
    	if(0.8 == scale){
    		DressCanvas.width = other.width/1;
            DressCanvas.height = other.height/1;
            var Tother = new createjs.Bitmap(other);
            Tother.scaleX=1;
            Tother.scaleY=1;
    	}else{
    		DressCanvas.width = other.width/2;
            DressCanvas.height = other.height/2;
            var Tother = new createjs.Bitmap(other);
            Tother.scaleX=0.5;
            Tother.scaleY=0.5;
    	}
        
        DressStage.addChild(Tother);
        DressStage.update();
        var photos = DressStage.toDataURL();//生成图片地址，1为质量
        if (photos) {
            Addicofun(idName,photos);
        }
    }
}

function AddRen() {
    var _url="img/"+_sex+"/"+_chang+'/'+_zishi+"/b" + PerArr[0] + ".png";
    AddRenTemp(_url);
}
function AddYiFu(){
	var _url="img/"+_sex+"/"+_chang+"/"+_zishi+"/yf" + PerArr[1] + ".png?=2";
    AddRenTemp(_url);
}
function AddCWFu(){
	var _url="img/cw/b" + PerArr[3] + ".png";
	var _idName='cw'+PerArr[3];		
	AddOther(_idName,_url, 0.5);
}
function AddDaoJu(){
	var _url="img/dj/b" + PerArr[4] + ".png";
	var _idName='dj'+PerArr[4];
	AddOther(_idName,_url, 0.5);
}
function AddWenZi(){
	var _url="img/wz/b" + PerArr[5] + ".png";
	var _idName='wz'+PerArr[5];
	AddOther(_idName,_url, 0.8);
}

 

//添加边框效果
var BorderBox = new createjs.Container();
var border_s, Tdel;

function addCtr(ctrEle) {
    BorderBox.removeAllChildren();
    stage.removeChild(BorderBox);
    border_s = new createjs.Shape();
    border_s.graphics.setStrokeStyle(2).beginStroke("#0188fb").drawRect(0, 0, ctrEle["image"].width, ctrEle["image"].height);
// .setStrokeDash([10, 5], 0)//虚线
    border_s.regX = ctrEle.regX;
    border_s.regY = ctrEle.regY;
    BorderBox.rotation = ctrEle.rotation;
    border_s.scaleX = ctrEle.scaleX;
    border_s.scaleY = ctrEle.scaleY;
    BorderBox.x = ctrEle.x;
    BorderBox.y = ctrEle.y;
    var imgdel = new Image();
    imgdel.src = "Public/img/delete.png";
    imgdel.onload = function () {
        Tdel = new createjs.Bitmap(imgdel);
        // Tdel.rotation=ctrEle.rotation;
        TdelMove();
        BorderBox.addChild(border_s, Tdel);
        stage.addChild(BorderBox);
        Tdel.on("click", function (evt) {
            if (ctrEle) {
                // Btnmusic.play();
                deleteCtr(true);
            }
        });
    }
}

// 删除选中效果
function deleteCtr(delIco) {
    if (!ctrEle) return;
    stage.removeChild(BorderBox);
    var _idName=ctrEle.idName;
    
    console.log(_idName.substr(0,2));
    console.log(_idName.substr(2));
    if (delIco) {
        // if (remCtrEle) {
        //     remCtrEle = null;
        // }
    	if('cw' == _idName.substr(0,2)){
        	_chongisF[_idName.substr(2)]=0;
        }
    	if('dj' == _idName.substr(0,2)){
    		_daoisF[_idName.substr(2)]=0;
        }
    	if('wz' == _idName.substr(0,2)){
    		_wenisF[_idName.substr(2)]=0;
        }
    	
    	
     
        stage.removeChild(ctrEle.parent);
    }

}

function TdelMove() {
    Tdel.x = (border_s.x - ctrEle["image"].width / 2) * ctrEle.scaleX - Tdel["image"].width / 2;
    Tdel.y = (border_s.y + ctrEle["image"].height / 2) * ctrEle.scaleX - Tdel["image"].height / 2;
    // Tmove.x = (border_s.x + ctrEle["image"].width / 2) * ctrEle.scaleX - Tmove["image"].width / 2;
    // Tmove.y = (border_s.y - ctrEle["image"].height / 2) * ctrEle.scaleX - Tmove["image"].height / 2;
}

var curStatus = 0; //记录当前手势的状态, 0:拖动, 1:缩放, 2:旋转
touch.on('#canvas', 'touchstart', function (ev) {
    if (!update) {
        return false;
    }
    curStatus = 0;
    scaleVal = ctrEle.scaleX;
    ev.preventDefault(); //阻止默认事件
});
// 开始拖动
touch.on('#canvas', 'drag', function (ev) {
    if (!update) {
        return false;
    }
    ctrEle.x = lefts + ev.x;
    ctrEle.y = tops + ev.y;
    BorderBox.x = lefts + ev.x;
    BorderBox.y = tops + ev.y;

});
// 拖动结束
touch.on('#canvas', 'dragend', function (ev) {
    if (!update) {
        return false;
    }
    lefts = lefts + ev.x;
    tops = tops + ev.y;
});
touch.on('#canvas', 'pinch rotate', function (ev) {
    if (!update || BorderBox.children.length != 2) {
        return false;
    }
    var ss = scaleVal * ev.scale;
    if (ss < 0.1) {
        return false;
    }
    ctrEle.scaleX = ctrEle.scaleY = ss;
    border_s.scaleX = border_s.scaleY = ss;
    TdelMove();
    var totalAngle = rotates + ev.rotation;
    if (ev.fingerStatus === 'end') {
        rotates = rotates + ev.rotation;
    }
    ctrEle.rotation = BorderBox.rotation = totalAngle;
});
// touch.on('#canvas', 'pinchend', function (ev) {
//     console.log(ev)
// });

// touch.on('#canvas', 'tap', function (ev) {
//     console.log(ev)
//     deleteCtr();
//     update=false
// });
 